<?php

namespace App\Http\Model;

use App\Http\Controllers\UploadController;
use Illuminate\Database\Eloquent\Model;

class NavModel extends Model
{
    protected $table = "pre_nav";

    public function img(){
        return $this->hasOne("App\Http\Model\ImgModel","imgId","picture");
    }

    public function addNav($position,$data){

        \DB::beginTransaction();

        try {

            NavModel::where("position_id",$position)->update(["states"=>9]);

            foreach ($data as $n) {

                $navModel = new NavModel();

                $im = new ImgModel();

                $uc = new UploadController();

                $tmpNav ="";

                if(array_key_exists("id",$n)){

                    $navModel = $navModel->where("id",$n->id)->first();

                }

                $navModel->position_id = $position;

                $navModel->ntitle = $n->ntitle;

                if(explode("/",$n->picture)[0]=="tmp") {

                    $uuid = $uc->moveImg($n->picture);

                    $im->imgId = $uuid;

                    $im->file = date("/Y/m/d/") . (explode("/", $n->picture)[1]);

                    $im->save();

                    $navModel->picture = $uuid;
                }

                $navModel->states = $n->states==true?1:2;

                $navModel->link_type = $n->link_type;

                $navModel->link_target = $n->link_target;

                $navModel->save();
            }

            \DB::commit();

            return "success";
        }catch (Exception $e) {
            \DB::rollback();

            return "error";
        }
    }

    public function updateNav($data){
        $res = \DB::table("pre_nav")->where("id",$data["id"])->update($data);

        return $res;
    }

    public function delNav($id){
        $res = \DB::table("pre_nav")->where("id",$id)->update([
            "states"=>9
        ]);
        return $res;
    }

    public function selectNav($id){

//        $res = \DB::table("pre_nav")->where("position_id",$id)
//            ->where("states","!=",9)
//            ->select("id","ntitle","link_type","link_target","picture","states")
//            ->get();


        $res = NavModel::where("position_id",$id)->where("states","!=",DELETE_STATUS)
            ->SELECT("id","ntitle","link_type","link_target","picture","states")
            ->with(["img"=>function($query){
              $query->select("file","imgId");
            }])
            ->get();


        return $res;
    }
}
